package com.hup.utils.commons.exception.parser;

import com.hup.utils.commons.exception.AppExceptionHandler;
import com.hup.utils.commons.exception.CauseException;
import com.hup.utils.commons.exception.ErrInfo;
import com.hup.utils.commons.exception.ErrParserRegister;
import com.hup.utils.commons.exception.ExceptionMsgParser;
import com.hup.utils.commons.exception.TraceHandler;
import org.springframework.beans.factory.BeanCreationException;

import java.util.ArrayList;
import java.util.List;

/**
 * 注册时,需要有以下依赖
 * @author hugan
 * @date 2019/9/10
 */
public class SpringStartMsgParser implements ErrParserRegister {

    @Override
    public List<ExceptionMsgParser> getParsers() {
        ArrayList<ExceptionMsgParser> list = new ArrayList<>();
        list.add(new BeanCreation());
        return list;
    }

    private static class BeanCreation implements ExceptionMsgParser<BeanCreationException> {
        @Override
        public String getMsg(BeanCreationException e) {
            return null;
        }

        @Override
        public ErrInfo getInfo(String msgHead, BeanCreationException e) {
            Throwable cause = e;
            while (cause.getCause() != null) {
                cause = cause.getCause();//获取最里面的出现错误的信息
                if (cause instanceof CauseException) break;
            }
            ErrInfo causeInfo = AppExceptionHandler.handleNoLog("[" + e.getBeanName() + "]初始化异常:", cause);

            ErrInfo res = new ErrInfo();
            res.setMsg(msgHead, causeInfo.getErrMsg());
            res.setTrace(getTrace(e) + TraceHandler.TRACE_HANDLER.getTrace(cause));
            return res;
        }
    }
}
